package com.dragonwu.config;

import com.dragonwu.filter.TokenAuthenticationFilter;
import com.dragonwu.handler.AccessDeniedHandlerImpl;
import com.dragonwu.handler.AuthenticationEntryPointImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
import java.util.Collections;

/**
 * @author DragonWu
 * @since 2022-10-06 21:14
 **/
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)  //开启权限访问注解
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //允许匿名访问的
    private static final String[] ALLOW_ASK = {
            "/login",
            "/captcha"
    };
    //总数允许访问的
    private static final String[] ALWAYS_ALLOW_ASK = {
            "/v2/api-docs",
            "/swagger-resources/configuration/ui",//用来获取支持的动作
            "/swagger-resources",//用来获取api-docs的URI
            "/swagger-resources/configuration/security",//安全选项
            "/webjars/**",
            "/swagger-ui.html",//以上为api文档接口访问路径
            "/static/**",//放行静态资源
            "**/open" //开放访问的资源
    };

    //自定义登录
    @Autowired
    private UserDetailsService userDetailsService;

    //token过滤器
    @Autowired
    private TokenAuthenticationFilter tokenAuthenticationFilter;

    //禁止访问异常处理器
    @Autowired
    private AccessDeniedHandlerImpl accessDeniedHandler;

    //认证异常处理器
    @Autowired
    private AuthenticationEntryPointImpl authenticationEntryPoint;

    /*
    密码加密器
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /*
     设置自定义登录逻辑
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    /*
    自定义登录，用户认证
     */
    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    /*
    页面资源授权
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                //对应登录接口允许匿名访问
                .antMatchers(ALWAYS_ALLOW_ASK).permitAll()
                .antMatchers(ALLOW_ASK).anonymous()
                //除上面接口全都需要鉴权访问
                .anyRequest().authenticated();

        //添加过滤器
        http.addFilterBefore(tokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        //添加异常处理器
        http.exceptionHandling()
                //认证失败的处理器
                .authenticationEntryPoint(authenticationEntryPoint)
                //授权失败处理器
                .accessDeniedHandler(accessDeniedHandler);

        //跨域配置
        http.cors()
                .configurationSource(corsConfigurationSource());

    }

    /*
     跨域配置对象
     */
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        //配置允许访问的服务器域名
        configuration.setAllowedOrigins(Collections.singletonList("*"));
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE"));
        configuration.setAllowedHeaders(Collections.singletonList("*"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}
